/*
 * QNoteListItemModel.h
 *
 *  Created on: Sep 8, 2010
 *      Author: alex
 */

#ifndef QNOTELISTITEMMODEL_H_
#define QNOTELISTITEMMODEL_H_

#include <QAbstractListModel>
#include "QvernoteAPI.h"
#include "QEnmlReader.h"

class QNoteListItemModel : public QAbstractListModel
{
	Q_OBJECT;

public:
	QNoteListItemModel(vector<Note> noteList, QObject* parent = 0)
	: QAbstractListModel(parent), m_NoteList(noteList) {
		for(int i = 0; i < m_NoteList.size(); i++)
			m_NoteMarkList[i] = false;
	}

	QNoteListItemModel(const QString filterString = "", QObject* parent = 0)
	: QAbstractListModel(parent) {
		QvernoteAPI* api = QvernoteAPI::Instance();
		Note note;
		bool hasMoreNotes;

		for(hasMoreNotes = api->getFirstNote(note); hasMoreNotes; hasMoreNotes = api->getNextNote(note))
		{
			if(QString::fromStdString(note.title).startsWith(filterString, Qt::CaseInsensitive))
			{
				m_NoteList.push_back(note);
				m_NoteMarkList.push_back(false);
			}
		}
	}

	int rowCount(const QModelIndex &parent = QModelIndex()) const {
		return m_NoteList.size();
	}

	QVariant data(const QModelIndex &index, int role) const {
		if (role == Qt::DisplayRole) {
			const Note* nPtr = &m_NoteList[index.row()];
			return QVariant((int)nPtr);
		}

                else if(role == Qt::CheckStateRole) {
                    return (m_NoteMarkList[index.row()])? Qt::Checked : Qt::Unchecked;
                }

                else if(role == Qt::DecorationRole) {
                    Note* note_p = (Note*)&m_NoteList[index.row()];
                    QByteArray  thumbnail;
                    QPixmap*    thumbnailImage;

                    if(! QvernoteStorage::Instance()->getNoteThumbnail(note_p->guid, thumbnail))
                    {
                        QvernoteAPI::Instance()->getNoteContent(*note_p);
                        QEnmlReader* enml_reader = new QEnmlReader(*note_p);
                        enml_reader->setLoadExternalReferences(false);
                        enml_reader->parse();
                        enml_reader->createThumbnail();
                        delete enml_reader;
                    }

                    thumbnailImage = new QPixmap();
                    thumbnailImage->loadFromData(thumbnail);
                    return QVariant((char*)thumbnailImage);
                }

		return QVariant();
	}

	Note& getNote(const QModelIndex& index) {
		return m_NoteList[index.row()];
	}

	void toggleMark(const QModelIndex& index) {
		m_NoteMarkList[index.row()] = !m_NoteMarkList[index.row()];
		if(m_NoteMarkList[index.row()] == true)
			emit noteMarked();
		else
			emit noteUnmarked();
	}

	bool isMarked(const QModelIndex& index) {
		return m_NoteMarkList[index.row()];
	}

signals:
	void noteMarked();
	void noteUnmarked();

private:
	vector<Note> m_NoteList;
	vector<bool> m_NoteMarkList;
};
#endif /* QNOTELISTITEMMODEL_H_ */
